/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2020 All Rights Reserved.
 */
package com.suxiaoxiao.springbootlearn.designpattern.statepattern.goodcode.stateimpl;

import com.suxiaoxiao.springbootlearn.designpattern.statepattern.goodcode.State;
import com.suxiaoxiao.springbootlearn.designpattern.statepattern.goodcode.pojo.GumballMachine;

import java.util.Random;

/**
 * 已投币状态
 *
 * @author zhaorongzhang
 * @version HasQuarterState.java, v 0.1 2020/1/9 9:34 下午 zhaorongzhang Exp $$
 */
public class HasQuarterState extends State {

    Random randomWinner = new Random(System.currentTimeMillis());

    /**
     * 网络传输中，我们并不希望序列化这个字段，所以我们加上 transient 告诉 JVM 不需要序列化这个字段。
     */
    transient GumballMachine gumballMachine;

    public HasQuarterState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void ejectQuarter() {
        System.out.println("退款中");
        gumballMachine.setState(gumballMachine.getNoQuarterState());
    }

    @Override
    public void turnCrank() {
        System.out.println("转动句柄中");
        int winner = randomWinner.nextInt(10);
        if (winner == 0 && gumballMachine.getCount() > 1) {
            gumballMachine.setState(gumballMachine.getWinnerState());
        } else {
            gumballMachine.setState(gumballMachine.getSoldState());
        }
    }

}